<template>
  <!-- 专利：国内外趋势分析 -->
  <div>
    <div ref="fullScreenBox" :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt, thousands } from "@/utils/utils";
import * as echarts from "echarts";

export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String,
    },
    chartData: {
      type: Object,
    },
  },
  data() {
    return {
      chart: null,
      graphType: "bar",
      colors: [],
      xData: [],
      yData: [],
      legendData: [],
    };
  },
  computed: {
    ...mapState(["curChartConfig"]),
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function() {
        this.getCurChartConfig();
      },
    },
    chartData: {
      deep: true,
      handler: function() {
        if (Object.keys(this.chartData).length <= 0) {
          if (this.chart) this.chart.clear();
        } else {
          this.getCurChartConfig();
        }
      },
    },
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.$emit("domRef", document.getElementById(this.chartId))
    this.getCurChartConfig();
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach((v) => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "line") {
          graphType = "line";
        }
        this.graphType = graphType;
      }
      if (Object.keys(this.chartData).length > 0) {
        if (this.curChartConfig.graphType === "line") {
          this.initline();
        } else {
          this.initbar();
        }
      }
    },
    getSeriesData() {
      let seriesData = {
        all: [],
        faming: [],
        xarr: [],
      };
      let newChartData = JSON.parse(JSON.stringify(this.chartData.apd));
      let xarr = [],
        all = [],
        faming = [];
      newChartData.forEach((data) => {
        xarr.push(data.key_as_string);
        if (data.nd.length) {
          data.nd.forEach((d) => {
            if (d.key == "国内") {
              all.push(d.doc_count);
            } else if (d.key == "国外") {
              faming.push(d.doc_count);
            }
          });
        }
      });
      seriesData = {
        all: all,
        faming: faming,
        xarr: xarr,
      };
      return seriesData;
    },
    initline() {
      let seriesData = this.getSeriesData();
      // 轴线
      let xAxisLine = {
        lineStyle: {
          color:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].color
              : "#77777",
          width: 1,
          type:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].type
              : "solid",
        },
      };
      // x轴分隔线
      let xSplitLine = {
        show:
          this.curChartConfig["xGridLine"] &&
          this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["xGridLine"] &&
              this.curChartConfig["xGridLine"].color) ||
            "#f0f1f3",
          type:
            this.curChartConfig["xGridLine"] &&
            this.curChartConfig["xGridLine"].type,
        },
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type,
        },
      };
      // 背景色
      let backgroundColor =
        this.curChartConfig["showBgColor"] &&
        this.curChartConfig["showBgColor"].checked
          ? this.curChartConfig["showBgColor"].color
          : "#fff";

      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
            "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };
      let color = [
        "#0092f6",
        "#00d4c7",
        "#aecb56",
        "#FF515A",
        "#8B5CFF",
        "#00CA69",
      ];
      let option = {
        color: color,
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        legend: {
          show: this.curChartConfig["showLegend"],
          x: "center",
          y: "0",
          icon: "stack",
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: "#1bb4f6",
          },
          data: ["国内", "国外"],
        },
        // 背景色
        backgroundColor: backgroundColor,
        toolbox: {
          feature: {
            // saveAsImage: {}
          },
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: true,
            splitLine: xSplitLine,
            data: seriesData.xarr,
          },
        ],
        yAxis: [
          {
            type: "value",
            splitLine: ySplitLine,
          },
        ],
        series: [
          {
            name: "国内",
            type: "line",
            zlevel: 3,
            symbol: "circle",
            symbolSize: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  textStyle: {
                    color: "#6b6c7e"
                  },
                  position: "top",
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                },
                color: "#0092f6",
                lineStyle: {
                  color: "#0092f6",
                  width: 1,
                },
                areaStyle: {
                  //color: '#94C9EC'
                  color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                    {
                      offset: 0,
                      color: "rgba(255,255,255,0.1)",
                    },
                    {
                      offset: 1,
                      color: "rgba(0,146,246,1)",
                    },
                  ]),
                },
              },
            },
            data: seriesData.all,
          },
          {
            name: "国外",
            type: "line",
            symbol: "circle",
            symbolSize: 8,
            zlevel: 3,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  textStyle: {
                    color: "#6b6c7e"
                  },
                  position: "top",
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                },
                color: "#00d5f5",
                lineStyle: {
                  color: "#00d5f5",
                  width: 1,
                },
                areaStyle: {
                  //color: '#94C9EC'
                  color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                    {
                      offset: 0,
                      color: "rgba(255,255,255,0.1)",
                    },
                    {
                      offset: 1,
                      color: "rgba(0,213,245,1)",
                    },
                  ]),
                },
              },
            },
            data: seriesData.faming,
          },
        ],
      };

      if (this.graphType !== "pie") {
        option.tooltip.trigger = "axis";
        // option.color = this.colors;
      } else {
        let formatter = (params) => {
          let str = `${params.marker}${params.data.name}：${params.data.value}`;
          return str;
        };
        option.grid = {
          top: "50px",
          right: "20px",
          left: "20px",
          bottom: "20px",
          containLabel: true,
        };

        option.tooltip.trigger = "item";
        option.tooltip.formatter = formatter;
        option.xAxis.show = false;
        option.yAxis.show = false;
      }
      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },

    initbar() {
      let seriesData = this.getSeriesData();
      // 轴线
      let xAxisLine = {
        lineStyle: {
          color:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].color
              : "#77777",
          width: 1,
          type:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].type
              : "solid",
        },
      };
      // x轴分隔线
      let xSplitLine = {
        show:
          this.curChartConfig["xGridLine"] &&
          this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["xGridLine"] &&
              this.curChartConfig["xGridLine"].color) ||
            "#f0f1f3",
          type:
            this.curChartConfig["xGridLine"] &&
            this.curChartConfig["xGridLine"].type,
        },
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type,
        },
      };
      // 背景色
      let backgroundColor =
        this.curChartConfig["showBgColor"] &&
        this.curChartConfig["showBgColor"].checked
          ? this.curChartConfig["showBgColor"].color
          : "#fff";

      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
            "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };
      let color = [
        "#0092f6",
        "#00d4c7",
        "#aecb56",
        "#FF515A",
        "#8B5CFF",
        "#00CA69",
      ];
      let option = {
        color: color,
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // type: "shadow",
          },
          // formatter: (params) => {
          //   var res = "";
          //   for (var i = 0; i < params.length; i++) {
          //     if (params[i].seriesName != "总计") {
          //       // 这行代码就是判断语句 具体情况 具体分析  自己打印params 来实现自己的判断
          //       res += `<div style="background:none">
          //         ${params[i].seriesName}
          //         ${params[i].data}
          //       </div>`;
          //     }
          //   }
          //   return res; //最后返回的数据得一个字符串 并且支持html css 显示我用的都是行内式样式 拼接成一个字符串 给最后显示 数遍悬浮的样式也是在这里设置 你的字符串是什么样式  渲染出来就是什么样的
          // },
        },
        // toolbox: {
        //   feature: toolboxFullScreen(this.$refs.fullScreenBox),
        // },
        legend: {
          show: this.curChartConfig["showLegend"],
          x: "center",
          y: "0",
          icon: "stack",
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: "#1bb4f6",
          },
          data: ["国内", "国外"],
        },
        // 背景色
        backgroundColor: backgroundColor,
        toolbox: {
          feature: {
            // saveAsImage: {}
          },
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: true,
            splitLine: xSplitLine,
            data: seriesData.xarr,
          },
        ],
        yAxis: {
          type: "value",
          splitLine: ySplitLine,
          minInterval: 1,
        },
        smooth: false,
        series: [
          {
            name: "国内",
            stack: "sum",
            type: "bar",
            barMaxWidth: 35,
            barMinWidth: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  textStyle: {
                    color: "#fff",
                  },
                  position: "inside",
                  fontSize: "11",
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  },
                },
              },
            },

            data: seriesData.all,
          },
          {
            name: "国外",
            type: "bar",
            stack: "sum",
            barMaxWidth: 35,
            barMinWidth: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  fontSize: "11",
                  textStyle: {
                    color: "#fff",
                  },
                  position: "inside",
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  },
                },
              },
            },

            data: seriesData.faming,
          },
        ],
      };
      if (this.graphType !== "pie") {
        option.tooltip.trigger = "axis";
      } else {
        let formatter = (params) => {
          let str = `${params.marker}${params.data.name}：${params.data.value}`;
          return str;
        };
        option.grid = {
          top: "50px",
          right: "20px",
          left: "20px",
          bottom: "20px",
          containLabel: true,
        };
        option.tooltip.trigger = "item";
        option.tooltip.formatter = formatter;
        option.xAxis.show = false;
        option.yAxis.show = false;
      }
      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },

    getEchartImg(base) {
      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      window.echartImg = base;
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    },
  },

  destroyed() {
    this.chart.dispose();
    this.chart = null;
  },
};
</script>

<style lang="scss" scoped>
// .chart {
//   background-color: #fff;
// }
</style>
